<template>
    <div class="add">
        <div class="container">
            <div class="main">
                <p class="title">账号信息</p>
                <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="90" class="box">
                    <!-- 登录账号 -->
                    <FormItem prop="userName" label='登录账号：'>
                        <Input v-model.trim="formValidate.userName" placeholder="请输入登录账号" style="width: 500px" maxlength="16"></Input>
                    </FormItem>
                    <!-- 登录密码 -->
                    <FormItem  v-if="flag" prop="passWord"  label='登录密码：'>
                        <Input v-model.trim="formValidate.passWord" :placeholder="tip" style="width: 500px" type="password" maxlength="16" autocomplete="new-password"></Input>
                        <img src="../../../../../assets/images/close.png" @click="handlePassword" alt="" class="eye">
                    </FormItem>
                    <FormItem v-else prop="passWord"  label='登录密码：'>
                        <Input v-model.trim="formValidate.passWord" :placeholder="tip" style="width: 500px" type="text" autocomplete="new-password"></Input>
                        <img src="../../../../../assets/images/open.png" @click="handlePassword" alt="" class="eye">
                    </FormItem>
                    <FormItem prop="phone" label='手机号码：'>
                        <Input v-model.trim="formValidate.phone" placeholder="请输入用户手机号" number style="width: 500px" autocomplete="off"  id='phone' maxlength="11"/>
                    </FormItem>
                    <!-- 用户昵称 -->
                    <FormItem prop="nickName" label='用户昵称：'>
                        <Input v-model.trim="formValidate.nickName" placeholder="请设置用户昵称" style="width: 500px" maxlength="10"></Input>
                    </FormItem>
                    <!-- 用户头像 -->
                    <FormItem label='用户头像：'>
                    <div class="input">
                            <div class="demo-upload-list" v-for="(item,index) in uploadList" :key='index'>
                                <div v-if="item.status === 'finished'">
                                    <img :src="item.url">
                                    <div class="demo-upload-list-cover">
                                        <Icon
                                            type="ios-eye-outline"
                                            @click.native="handleView(item.name)"
                                        ></Icon>
                                        <Icon
                                            type="ios-trash-outline"
                                            @click.native="handleRemove(item)"
                                        ></Icon>
                                    </div>
                                </div>
                                <div v-else>
                                    <Progress
                                        v-if="item.showProgress"
                                        :percent="item.percentage"
                                        hide-info
                                    ></Progress>
                                </div>
                            </div>
                            <Upload
                                v-show="uploadList.length ==0"
                                ref="upload"
                                :show-upload-list="false"
                                :default-file-list="defaultList"
                                :on-success="handleSuccess"
                                :format="['jpg','jpeg','png']"
                                :max-size="2000"
                                :on-format-error="handleFormatError"
                                :on-exceeded-size="handleMaxSize"
                                :before-upload="handleBeforeUpload"
                                multiple
                                type="drag"
                                :action="uploadUrl"
                                :headers="fromData"
                                :data="uploadData"
                                style="display: inline-block;width:58px;"
                            >
                                <div style="width: 58px;height:58px;line-height: 58px;">
                                    <Icon type="ios-camera" size="20"></Icon>
                                </div>
                            </Upload>
                            <Modal title="预览图片" v-model="visible" footer-hide  :transfer="false">
                                <img :src="uploadList[0].url " v-if="visible" style="width: 100%">
                            </Modal>
                        </div>
                    </FormItem>
                    <!-- 用户身份 -->
                    <FormItem prop="identityAdd" label='用户身份：'>
                        <div>
                            <Select class="w-select-identity" placeholder="用户身份" v-model="formValidate.identityAdd">
                                <Option
                                    v-for="item in identityList"
                                    :value="item.id"
                                    :key="item.id"
                                    style='text-align:center;'
                                >{{item.name}}</Option>
                            </Select>
                        </div>
                    </FormItem>
                    <!-- 用户所属 -->
                    <FormItem label='用户所属：'>
                        <div>
                            <Select
                                class="w-select"
                                @on-change="changeProvince"
                                placeholder="省"
                                v-model="provinceId"
                                :clearable="!provinceStatus"
                                :disabled="provinceStatus"
                                v-if="formValidate.identityAdd >= 2 || formValidate.identityAdd == 5"
                            >
                                <Option
                                    v-for="item in provinceList"
                                    :value="item.id"
                                    :key="item.id"
                                    style='text-align:center;'
                                >{{item.name}}</Option>
                            </Select>
                            <Select
                                class="w-select"
                                @on-change="changeCity"
                                placeholder="市"
                                v-model="cityId"
                                :clearable="!cityStatus"
                                :disabled="cityStatus"
                                v-if="formValidate.identityAdd >= 3 || formValidate.identityAdd == 5"
                            >
                                <Option
                                    v-for="(item) in cityList"
                                    :value="item.id"
                                    :key="item.id"
                                    style='text-align:center;'
                                >{{item.name}}</Option>
                            </Select>
                            <Select
                                class="w-select"
                                @on-change="changeArea"
                                placeholder="区/县"
                                v-model="areaId"
                                :clearable="!areaStatus"
                                :disabled="areaStatus"
                                v-if="formValidate.identityAdd >= 4 || formValidate.identityAdd == 5"
                            >
                                <Option
                                    v-for="item in areaList"
                                    :value="item.id"
                                    :key="item.id"
                                    style='text-align:center;'
                                >{{item.name}}</Option>
                            </Select>
                            <Select
                                class="w-select-hos"
                                placeholder="医院"
                                @on-change="changeDepartment"
                                v-model="hospitalId"
                                :clearable="!hospitalStatus"
                                :disabled="hospitalStatus"
                                v-if="formValidate.identityAdd == 5"
                            >
                                <Option
                                    v-for="item in hospitalList"
                                    :value="item.id"
                                    :key="item.id"
                                    style='text-align:center;'
                                >{{item.orgName}}</Option>
                            </Select>
                        </div>
                    </FormItem>
                    <!-- 所属科室 -->
                    <FormItem label='所属科室：'>
                      <Select
                        class="w-select"
                        placeholder="科室"
                        v-model="department"
                        clearable
                      >
                        <Option
                          v-for="(item,index) in departmentList"
                          :value="item"
                          :key="index"
                          style='text-align:center;'
                        >{{item}}</Option>
                      </Select>
                    </FormItem>
                    <!-- 是否开启 -->
                    <FormItem label='是否开启：'>
                        <iSwitch v-model="switch1" size="large">
                            <span slot="open">启用</span>
                            <span slot="close">禁用</span>
                        </iSwitch>
                    </FormItem>
                </Form>

            </div>
            <div style="border-top: 1px dashed #999; margin-right:-32px"></div>
            <div style="width:100%px;text-align:center;padding: 20px 0px;">
                <Button type="primary" @click="save('formValidate')" :disabled='disabledSave' style="width:75px;height:35px;">
                    <Icon type="ios-checkmark" style="margin-right: 5px" />提交
                </Button>
                <Button @click="back" style="width:75px;height:35px;">
                    <i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>取消
                </Button>
            </div>
        </div>
    </div>
</template>
<script>
import api from "@/api/commonApi";
import code from "@/configs/base.js";
import { RadioGroup, Radio } from "view-design";
import cookie from "@/utils/cookie.js";
export default {
    components: {
        RadioGroup,
        Radio
    },
    data() {
        const validatePassword = (rule, value, callback) => {
         if (value === '') {
            callback(new Error('请输入新密码'));
            this.disabledSave = false
         } else {
              //6-20位包含字符、数字和特殊字符
              var ls = 0;
          if (this.formValidate.passWord !== '') {
              if(this.formValidate.passWord.match(/([a-z])+/)){
                ls++;
              }
              if(this.formValidate.passWord.match(/([0-9])+/)){
                ls++;
              }
              if(this.formValidate.passWord.match(/([A-Z])+/)){
                ls++;
              }
              if(this.formValidate.passWord.match(/([\W])+/) && !this.formValidate.passWord.match(/(![\u4E00-\u9FA5])+/)){ 
                ls++;
              }
              if(this.formValidate.passWord.length<8 || this.formValidate.passWord.length>16 ){
                  callback(new Error('要求8-16位字符'));
                  ls=0;
              }
              if(this.formValidate.passWord.match(/([\u4E00-\u9FA5])+/)){
                  callback(new Error('不能包含中文字符'));
                  ls=0;
              }
            if(cookie.getCookie("levelp") ==1){
                  switch (ls) {
                      case 0: this.passwordPercent = 0;callback(new Error('请设置登录密码(密码需8-16位)'));break;
                      case 3:
                      case 4: this.passwordPercent = 100;break;
                      default: this.passwordPercent = 0;break;
                  }
            }else if(cookie.getCookie("levelp") == 2){
                switch (ls) {
                  case 0: this.passwordPercent = 0;callback(new Error('密码需8-16位,包含字母和数字或特殊符号'));break;
                  case 1: this.passwordPercent = 33;callback(new Error('密码需8-16位,包含字母和数字或特殊符号'));break;
                  case 3:
                  case 4: this.passwordPercent = 100;break;
                  default: this.passwordPercent = 0;break;
              }
            }else if(cookie.getCookie("levelp") ==3){
                switch (ls) {
                  case 0: this.passwordPercent = 0;callback(new Error('密码需8-16位,包含字母和数字或特殊符号'));break;
                  case 1: this.passwordPercent = 33;callback(new Error('密码需8-16位,包含大小字母和数字或特殊符号'));break;
                  case 2: this.passwordPercent = 66;callback(new Error('密码需8-16位,包含大小字母和数字或特殊符号'));break;
                  case 3:
                  case 4: this.passwordPercent = 100;break;
                  default: this.passwordPercent = 0;break;
              }
            }
          }
          callback();
         }
        };
        return {
            tip:'',
            flag: true,
            passwordPercent:0,
			formValidate:{
				userName: "",
                //密码
                passWord: "",
                // 用户昵称
                nickName: "",
                phone:"",
				identityAdd: 5,
				identityAddCoding:""
			},
			ruleValidate:{
				// 登录账号
				userName:[
					{
						// 是否校验
						required: true,
						// 提示文字
						message: "请输入登录账号",
						// 触发事件
						trigger: "blur"
                    },
                    { message: "账号只可输入字母数字或_", trigger: "blur", pattern: /^[a-zA-Z0-9_]+$/ },
                    { message: "最多16个字符", trigger: "blur", max: 16 },
				],
				// 登录密码
				passWord:[
					{
						// 是否校验
						required: true,
						// 提示文字
						validator: validatePassword,
						// 触发事件
                        trigger: "blur",
					}
				],
				// 用户昵称
				nickName:[
					{
						// 是否校验
						required: true,
						// 提示文字
						message: "请输入用户昵称",
						// 触发事件
						trigger: "blur"
					}
                ],
                phone:[
                    {
                        type: 'number',
                        // 是否校验
                        required: true,
                        // 提示文字
                        message: "请输入用户手机号码",
                        // 触发事件
                        trigger: "blur"
                    }
                ],
				// 用户身份
				identityAdd:[
					{
						required: true,
						message: "请选择用户身份",
						trigger: "change"
					}
				],
				// 关联机构
				identityCoding:[
					{
						required: true,
						message: "请选择用户身份",
						trigger: "change"
					}
				],
			},
            switch1: true,
			// 上传图片相关
            defaultList: [],
            imgName: "",
            visible: false,
            uploadList: [],
            uploadModal: true,
            uploadData: {
                json: '{"urlCode":"' + code.urlCode.userImage + '"}'
            },
            activeUploadId: "5c2bf345-b973-4ffd-a52e-87bb9c1d2b72",
            uploadUrl: api.fileAll,
            images: "",

            identityList: [
                // {id:1,name:'超级管理员'},
                // { id: 2, name: "省级管理员" },
                // { id: 3, name: "市级管理员" },
                // { id: 4, name: "区级管理员" },
                // { id: 5, name: "机构配置管理员" }
			],
			// 区域列表
            provinceList: [],
            cityList: [],
			areaList: [],
			// 医院列表
            hospitalList: [],
			// 选中的区域
            provinceId: null,
            cityId: null,
            areaId: null,
            hospitalId: null,
            // 区域状态
            provinceStatus: false,
            cityStatus: false,
            areaStatus: false,
            hospitalStatus: false,
			// 用户身份
			identityAdd: 5,
			// 当前用户创建权限
			// 区域
			identityAddCoding: null,
			// 用户身份列表
			identity: null,
			// 机构代码/未用
			identityCoding: null,
			// 区县
            ownArea: null,
            disabledSave: false,
          //科室列表
          departmentList: [],
          department: null
        };
    },
    mounted() {
        this.uploadList = this.$refs.upload.fileList;
        // 关闭input框的自动填充
        setTimeout(() => {
            this.text = "";
            this.pass = "";
        });
    },
    created() {
        if(cookie.getCookie("levelp") == 1){
            this.tip = "请设置登录密码(密码需8-16位)"
        }else if(cookie.getCookie("levelp") == 2){
            this.tip = "请设置登录密码(密码需8-16位,包含字母和数字或特殊符号)"
        }else{
            this.tip = "请设置登录密码(密码需8-16位,包含大小字母和数字或特殊符号)"
        }
        let breadList = [
            { path: "/index", title: "首页" },
            {
                path: "/index/maintain/systemManagement/index",
                title: "帐号权限配置"
            },
            {
                path: "/index/maintain/admin/user/list",
                title: "账号管理"
            }
        ];
        this.$emit("changeBreadList", breadList);

        this.identity = cookie.getCookie("idtt");
		// this.identityCoding = cookie.getCookie("idttC");
		this.formValidate.identityCoding = cookie.getCookie("idttC");
		this.ownArea = JSON.parse(cookie.getCookie("ownArea"));
        if (this.ownArea.province) {
            this.provinceStatus = true;
            this.provinceList.push(this.ownArea.province);
            this.provinceId = this.ownArea.province.id;
        }
        if (this.ownArea.city) {
            this.cityStatus = true;
            this.cityList.push(this.ownArea.city);
            this.cityId = this.ownArea.city.id;
        }
        if (this.ownArea.area) {
          this.areaStatus = true;
            this.areaList.push(this.ownArea.area);
            this.areaId = this.ownArea.area.id;
        }

        if (this.identity == 1) {
            // this.identityList.push({ id: 2, name: "省级管理员" });
            // this.identityList.push({ id: 3, name: "市级管理员" });
            // this.identityList.push({ id: 4, name: "区级管理员" });
            this.identityList.push({ id: 5, name: "机构配置管理员" });
            this.provinceList = this.$store.getters.getProvinceList;
        } else if (this.identity == 2) {
            // this.identityList.push({ id: 3, name: "市级管理员" });
            // this.identityList.push({ id: 4, name: "区级管理员" });
            this.identityList.push({ id: 5, name: "机构配置管理员" });
            this.cityList = this.$store.getters.getCityList(this.provinceId);
        } else if (this.identity == 3) {
            // this.identityList.push({ id: 4, name: "区级管理员" });
            this.identityList.push({ id: 5, name: "机构配置管理员" });
            this.areaList = this.$store.getters.getAreaList(this.cityId);
        } else if (this.identity == 4) {
            this.identityList.push({ id: 5, name: "机构配置管理员" });
            var params = {};
            params.provinceCode = parseInt(this.provinceId);
            params.cityCode = parseInt(this.cityId);
            params.districtCode = parseInt(this.areaId);
            this.$axios
                .post(api.findHospitalListByProvinceCode, params)
                .then(resp => {
                    let list = resp.data.object;
                    list.map((el, i) => {
                        this.hospitalList.push({id:parseInt(el.id),orgName:el.orgName});
                    });
                })
                .catch(err => {
                    console.log(err);
                });
        } else if (this.identity == 5) {
            this.identityList.push({ id: 5, name: "机构配置管理员" });
            this.hospitalId = parseInt(this.formValidate.identityCoding);
            this.hospitalStatus = true;
            this.$axios
                .post(api.mechanismregSearch, {
                    id: parseInt(this.formValidate.identityCoding)
                })
                .then(resp => {
                    this.hospitalList.push({
                        id: resp.data.object.id,
                        orgName: resp.data.object.orgName
                    });
                })
                .catch(err => {});
		}
		this.identityList.forEach(item => {
			item.id = item.id.toString();
		})
        this.provinceList = this.$store.getters.getProvinceList;
    },
    methods: {
        handlePassword () {
            this.flag = !this.flag
        },
        changeProvince() {
            this.cityId = null;
            this.areaId = null;
            this.hospitalId = null;
            this.cityList = this.$store.getters.getCityList(this.provinceId);
            this.hospitalList = null;
        },
        changeCity() {
            this.areaId = null;
            this.hospitalId = null;
            this.areaList = this.$store.getters.getAreaList(this.cityId);
            this.hospitalList = null;
        },
        changeArea() {
            this.hospitalId = null;
            this.hospitalList = null;
            var params = {};
            params.provinceCode = parseInt(
                this.provinceId == 0 ? null : this.provinceId
            );
            params.cityCode = parseInt(
                this.cityId == 0 ? null : this.cityId
            );
            params.districtCode = parseInt(
                this.areaId == 0 ? null : this.areaId
            );
            console.log('参数',params)
            this.$axios
                .post(api.findHospitalListByProvinceCode, params)
                .then(resp => {
                    this.hospitalList = resp.data.object;
                    console.log(this.hospitalList)
                })
                .catch(err => {
                    console.log(err);
                });
        },
        changeDepartment(){
          console.log(this.hospitalId)
          var params = {};
          params.hospitalId = parseInt(
            this.hospitalId == 0 ? null : this.hospitalId
          );
          this.$axios
            .post(api.departmentList, params)
            .then(resp => {
              this.departmentList = resp.data.object;
            })
            .catch(err => {
              console.log(err);
            });
        },
        //账号权限配置-新增
        save(name) {
            this.disabledSave = true
			this.$refs[name].validate(valid => {
				if (valid) {
					// 必填项填写完成
                    let images = "";
                    // 上传
                    if (this.images != "") {
                        images = this.images;
                    } else if (this.sourceImages != "" && this.uploadList.length) {
                        images = this.sourceImages;
                        // 默认
                    } else {
                        images = "";
                    }

                    if (this.formValidate.identityAdd == 1) {

                    } else if (this.formValidate.identityAdd == 2) {
                        if (this.provinceId == null) {
                            this.$Message.info("请选择所属省");
                            this.disabledSave = false
                            return ;
                        }
                        this.formValidate.identityAddCoding = this.provinceId;
                    } else if (this.formValidate.identityAdd == 3) {
                        if (this.cityId == null) {
                            this.$Message.info("请选择所属市");
                            this.disabledSave = false
                            return ;
                        }
                        this.formValidate.identityAddCoding = this.cityId;
                    } else if (this.formValidate.identityAdd == 4) {
                        if (this.areaId == null) {
                            this.$Message.info("请选择所属区/县");
                            this.disabledSave = false
                            return ;
                        }
                        this.formValidate.identityAddCoding = this.areaId;
                    } else if (this.formValidate.identityAdd == 5) {
                        if (this.hospitalId == null) {
                            this.$Message.info("请选择所属机构");
                            this.disabledSave = false
                            return ;
                        }
                        this.formValidate.identityAddCoding = this.hospitalId;
                    }
                    if (this.department == null) {
                      this.$Message.info("请选择所属科室");
                      this.disabledSave = false
                      return ;
                    }
                    let params = {
                        // 账号
                        userName: this.formValidate.userName,
                        //手机号码
                        phone:this.formValidate.phone,
                        // 密码
                        passWord: this.formValidate.passWord,
                        // 用户昵称
                        nickName: this.formValidate.nickName,
                        // 是否启用
                        status: Number(this.switch1),
                        // 用户头像
                        userIcon: images,
                        // 用户身份
                        identity: parseInt(this.formValidate.identityAdd),
                        // 所属机构
                        identityCoding: parseInt(this.formValidate.identityAddCoding),
                        //所属科室
                        department: this.department
                    };
                    this.$axios.post(api.insertUser, params).then(res => {
                            if (res.data.code) {
                                let a = res.data.object.fail || res.data.object.success;
                                if(a == "用户名重复，请重新输入"){
                                    this.disabledSave = false
                                    this.$Message.info(a);
                                } else {
                                    if(this.uploadList.length>0){
                                        this.handleRemove(this.uploadList[0])
                                    }
                                    this.disabledSave = false
                                    this.back()
                                }
                            } else {
                                this.disabledSave = false
                                this.$Message.info("不允许访问");
                            }
                        })
				} else {
					// 必填项填写失败
                    this.disabledSave = false
					flag = true;
				}
			})

        },
        back() {
            this.formValidate.userName = ''
            this.formValidate.passWord = ''
            this.formValidate.phone = ''
            this.formValidate.nickName = ''
            this.formValidate.identityAdd = 5
            this.switch1 = true
            if(this.uploadList.length>0){
                this.handleRemove(this.uploadList[0])
            }
            console.log(this.ownArea)
            this.provinceId = this.ownArea.province ? this.ownArea.province.id : null;
            this.cityId = this.ownArea.city ? this.ownArea.city.id : null;
            this.areaId = this.ownArea.area ? this.ownArea.area.id : null;
            this.hospitalId = null;
            this.$emit('showaddModal');
        },
        handleView(name) {
            this.imgName = name;
            this.visible = true;
        },
        handleRemove(file) {
            const fileList = this.$refs.upload.fileList;
            this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
        },
        handleSuccess(res, file) {
            res = this.uploadFileDecrypt(res);
            if (res.code) {
                file.url = this.fileBaseUrl + res.object[0].fileName;
                this.images = JSON.stringify(res.object[0]);
                file.name = res.object[0].fileName;
            } else {
                this.$Message.info("上传失败,请重试");
            }
        },
        handleFormatError(file) {
            this.$Notice.warning({
                title: "上传失败",
                desc: "文件格式错误"
            });
        },
        handleMaxSize(file) {
            this.$Notice.warning({
                title: "文件过大",
                desc: `文件${file.name}过大，文件最大限制为2000KB`
            });
        },
        handleBeforeUpload(file) {
            const check = this.uploadList.length < 1;
            if (!check) {
                this.$Message.info("只能上传一张图片");
            }
            return check;
        },
        analysisImages(json) {
            try {
                json = JSON.parse(json);
                return json.fileName;
            } catch (error) {
                return "";
            }
        }
    },
};
</script>
<style lang="less" scoped>
.eye{
    width: 22px;
    height: 22px;
    margin: 0 0 0 -32px;
    position: relative;
    // z-index: 9999;
}
.demo-upload-list {
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
    margin-right: 4px;
}
// 关闭input文本框自动填充背景色黄色
input:-webkit-autofill { box-shadow: 0 0 0px 1000px white inset !important;}
.demo-upload-list img {
    width: 100%;
    height: 100%;
}
.demo-upload-list-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
    display: block;
}
.demo-upload-list-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
}
.w-select {
    width: 105px;
}
.w-select-hos {
    width: 180px;
}
.w-select-identity {
    width: 150px;
}
.add {
    width: 100%;
    background: #ffffff;
    box-sizing: border-box;
    .container {
        width: 100%;
        margin: 0 auto;
        .main{
            width: 98%;
            display: flex;
            flex-direction: column;
            margin: 10px auto;
            border: 1px solid #f0f0f0;
            box-shadow: 0 4px 3px #ebedf8;
            border-radius: 5px;
            margin-bottom: 20px;
            .title {
                font-size: 20px;
                padding-left: 15px;
                margin-bottom: 20px;
                color: #333;
                height: 40px;
                line-height: 40px;
                background: #ebedf8;
            }
            .box {
                // padding: 0 50px;
            }
        }
    }
}
</style>

